package datasource

import (
	"fmt"
	"io/ioutil"
	"log"

	"IrisService/models"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/json-iterator/go"
)

type DataSource struct {
	Host     string `json:"host"`
	Port     uint   `json:"port"`
	UserName string `json:"user"`
	Passwd   string `json:"passwd"`
	DbName   string `json:"db"`
}

type DSHelper struct {
	db *gorm.DB
}

func NewDSHelper() *DSHelper {
	return &DSHelper{}
}

func (u *DSHelper) GetDB() *gorm.DB {
	return u.db
}

func (u *DSHelper) LoadConfig(file_path string) bool {
	b, err := ioutil.ReadFile(file_path)
	if err != nil {
		log.Println("DB config read err")
		return false
	}

	dbConfig := new(DataSource)
	err = jsoniter.Unmarshal(b, dbConfig)
	if err != nil {
		log.Println("DB config read err")
		return false
	}

	dsn := GetDSN(dbConfig.UserName, dbConfig.Passwd,
		dbConfig.Host, dbConfig.Port, dbConfig.DbName)
	return u.QuickConnect(dsn)
}

func (u *DSHelper) createTable() {
	u.db.AutoMigrate(&models.GEntity{},
		&models.ChangeLogItem{},
		&models.EntryItem{})
}

func (u *DSHelper) HasTable(table_name string) bool {
	return u.db.HasTable(table_name)
}

func GetDSN(user string, passwd string,
	host string, port uint, db string) string {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True",
		user, passwd, host, port, db)
	return dsn
}

func (u *DSHelper) QuickConnect(dsn string) bool {
	var err error
	u.db, err = gorm.Open("mysql", dsn)
	if err != nil {
		log.Println("DB connect err")
		return false
	}

	u.db.DB().SetMaxIdleConns(20)   //最大打开的连接数
	u.db.DB().SetMaxOpenConns(1000) //设置最大闲置个数
	u.db.SingularTable(true)        //表生成结尾不带s
	// 启用Logger，显示详细日志
	// u.db.LogMode(true)
	u.createTable()
	return true
}
